//
//  HomeViewController.m
//  Home
//
//  Created by xiaoyang on 16/9/21.
//  Copyright © 2016年 FaLaoMiaoNetworkTechnologyCo. All rights reserved.
//

#import "FLMPinkageViewController.h"
#import "XLsn0wCollectionViewFlowLayout.h"
#import "FLMTenNineGoodsListCell.h"

#import "FLMTenNineFreeModel.h"
#import "FLMWebViewController.h"

//#import "FLMDeatilViewController.h"

@interface FLMPinkageViewController () <UICollectionViewDataSource, XLsn0wCollectionViewFlowLayoutDelegate, UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *goodslistModelArr; //商品数组

@property (nonatomic, strong) UIView *popView;
@property (assign, nonatomic) NSIndexPath *selectedIndexPath;//单选，当前选中的行
    
@end

@implementation FLMPinkageViewController

//懒加载
- (NSMutableArray *)goodslistModelArr
{
    if (!_goodslistModelArr) {
        _goodslistModelArr = [NSMutableArray array];
    }
    return _goodslistModelArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RGB(252, 236, 206);
    [self loadData];
    [self drawCollectionViewUI];
    [self.navigationController.navigationBar xlsn0w_setBackgroundColor:[UIColor clearColor]];
    
}

- (void)loadData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"uname"] = @"bhzhuo";
    parameters[@"upass"] = [BaseHttpRequest md5HexDigest:[NSString stringWithFormat:@"%@%@",@"123456",@"sos_5941m"]];
    parameters[@"code"] = @"";
    parameters[@"token"] = @"f2c8ec76b30527be791752cab0cf743c";
    parameters[@"h"] = @"141";
    
    __weak typeof(self) weakSelf = self;
    [[XLsn0wNetwork defaultNetwork] POST:NineURL
                                   token:nil
                                  params:parameters
                                 success:^(NSURLSessionDataTask *task, NSDictionary *JSONDictionary, NSString *JSONString) {
                                     NSLog(@"JSONString===%@", JSONString);
                                     
                                     //返回数据
                                     XLsn0wLog(@"JSONDictionary成功数据===%@", JSONDictionary);
                                     
                                     FLMTenNineFreeModel *model = [FLMTenNineFreeModel mj_objectWithKeyValues:JSONDictionary];
                                     
                                     weakSelf.goodslistModelArr = [model.msg.goodslist mutableCopy];
                                     
                                     [weakSelf.collectionView reloadData];
                                      [self.collectionView.mj_header endRefreshing];
                                     
                                 }
                                 failure:^(NSURLSessionDataTask *task, NSError *error, NSInteger statusCode, NSString *requestFailedReason) {
                                     //错误原因
                                     XLsn0wLog(@"错误数据requestFailedReason===%@", requestFailedReason);
                                     [self.collectionView.mj_header endRefreshing];
                                 }];
}

//设置导航条为透明色
-(void)setNavigationBarClear{
    
    //给导航条设置一个空的背景图使其透明化
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    
    
    //去除导航条透明后导航条下的黑线
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
}

//滑动隐藏导航栏
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];

    [_popView removeFromSuperview];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    [self.navigationController.navigationBar xlsn0w_setDefaultStyle];
//}


#pragma mark - UIScrollViewDelegate
#define NAVBAR_CHANGE_POINT 50
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    UIColor * color = [UIColor colorWithRed:0/255.0 green:175/255.0 blue:240/255.0 alpha:1];
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY < NAVBAR_CHANGE_POINT) {
        CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64));
        [self.navigationController.navigationBar xlsn0w_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
    } else {
        //[self.navigationController.navigationBar xlsn0w_setBackgroundColor:[color colorWithAlphaComponent:0]];
        [self setNavigationBarClear];
    }
}


#pragma mark - setup CollectionViewUI
- (void)drawCollectionViewUI {
    XLsn0wCollectionViewFlowLayout *layout = [[XLsn0wCollectionViewFlowLayout alloc] init];
    layout.xlDelegate = self;
    layout.enableStickyHeaders = YES;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH-44-40) collectionViewLayout:layout];
    [self.view addSubview:_collectionView];
    _collectionView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.1];
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    
    [_collectionView registerClass:[FLMTenNineGoodsListCell class] forCellWithReuseIdentifier:@"FLMTenNineGoodsListCell"];
    
    UILongPressGestureRecognizer *longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    longPressGr.minimumPressDuration = 0.5f;
    longPressGr.numberOfTouchesRequired = 1;
    [_collectionView addGestureRecognizer:longPressGr];
    //Add MJRefresh
    self.collectionView.mj_header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.collectionView.mj_header beginRefreshing];
}

- (void)longPressAction:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        //取到点击点位置CGPoint
        CGPoint point = [longPress locationInView:_collectionView];
        //可以获取我们在哪个cell上长按
        NSIndexPath *indexPath = [_collectionView indexPathForItemAtPoint:point];
        _selectedIndexPath = indexPath;
        //取到长按的那个cell
        FLMTenNineGoodsListCell *cell = [_collectionView dequeueReusableCellWithReuseIdentifier:@"FLMTenNineGoodsListCell" forIndexPath:_selectedIndexPath];
        //悬浮popView
        if (indexPath != nil) {
            [self drawPopViewWithCell:cell selectedIndex:indexPath.row];
        }
    }
}

//移除popView
- (void)dismissPopView:(UITapGestureRecognizer *)tapGesture {
    [_popView removeFromSuperview];
}

- (void)drawPopViewWithCell:(FLMTenNineGoodsListCell *)cell selectedIndex:(NSInteger)selectedIndex {
    [XLsn0wHUD showTipText:[NSString stringWithFormat:@"第%ld个Cell", (long)selectedIndex] superview:self.view duration:1 animated:YES];
    
    //draw popView
    if (_popView != nil) {//保持popView唯一性 只有一个 点击其他cell 之前被移除
        [_popView removeFromSuperview];
    }
    _popView = [[UIView alloc] initWithFrame:cell.bounds];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissPopView:)];
    [_popView addGestureRecognizer:tapGesture];
    [cell addSubview:_popView];
    _popView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    
    //draw recommendButton
    UIButton *recommendButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [_popView addSubview:recommendButton];
    [recommendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(60*kFitHeight);
        make.centerX.mas_equalTo(_popView);
        make.width.mas_equalTo(60*kFitWidth);
        make.height.mas_equalTo(60*kFitWidth);
    }];
    [recommendButton setTitle:@"推荐" forState:(UIControlStateNormal)];
    [recommendButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [recommendButton addTarget:self action:@selector(recommendButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    recommendButton.backgroundColor = [UIColor blueColor];
    recommendButton.layer.borderWidth = 1;
    recommendButton.layer.borderColor = [[UIColor blueColor] CGColor];
    recommendButton.layer.cornerRadius = 30*kFitWidth;
    recommendButton.layer.masksToBounds = YES;
    
    //draw collectButton
    UIButton *collectButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [_popView addSubview:collectButton];
    [collectButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-60*kFitHeight);
        make.centerX.mas_equalTo(_popView);
        make.width.mas_equalTo(60*kFitWidth);
        make.height.mas_equalTo(60*kFitWidth);
    }];
    [collectButton setTitle:@"收藏" forState:(UIControlStateNormal)];
    [collectButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [collectButton addTarget:self action:@selector(collectButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    collectButton.backgroundColor = [UIColor orangeColor];
    collectButton.layer.borderWidth = 1;
    collectButton.layer.borderColor = [[UIColor orangeColor] CGColor];
    collectButton.layer.cornerRadius = 30*kFitWidth;
    collectButton.layer.masksToBounds = YES;
}

- (void)recommendButtonAction:(UIButton *)recommendButton {
    [XLsn0wHUD showTipText:@"执行推荐方法" superview:self.view duration:1 animated:YES];
}

- (void)collectButtonAction:(UIButton *)collectButton {
    [XLsn0wHUD showTipText:@"执行收藏方法" superview:self.view duration:1 animated:YES];
}

#pragma mark - UICollectionViewDelegate
- (void )collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
  
    //获取模型
    FLMTenNineGoodslistModel *item = self.goodslistModelArr[indexPath.row];
    
    if (![item.pict_url containsString:@"http"]) return;
    
    NSURL *url = [NSURL URLWithString:item.pict_url];
    
    FLMWebViewController *webVc = [[FLMWebViewController alloc] init];
    
    webVc.url = url;
    
    [self.navigationController pushViewController:webVc animated:YES];
 
}
#pragma mark - UICollectionViewLayout
    
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 6;
}
    
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 6;
}
    
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(7, 7, 7, 7);
}
    
#define ItemCellWidth ([UIScreen mainScreen].bounds.size.width - 20)/2
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(ItemCellWidth, 210 * (ItemCellWidth/150));
}
    
#pragma mark - XLsn0wCollectionViewFlowLayoutDelegate
    
- (NSInteger)collectionView:(UICollectionView *)collectionView
                     layout:(XLsn0wCollectionViewFlowLayout *)layout
   numberOfColumnsInSection:(NSInteger)section {
    return 2;
}
    
#pragma mark - UICollectionViewDataSource
    
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
    
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.goodslistModelArr.count;
//    return 6;
}
    
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FLMTenNineGoodsListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FLMTenNineGoodsListCell" forIndexPath:indexPath];
    [cell configueCellWithModel:self.goodslistModelArr[indexPath.row]];
    
    //得到后台传过来的BOOL 选择是否执行显示方法 当前显示3个
    [cell isHiddenLimitedTimePic];
    [cell isHiddenTodayNewPic];
    [cell isHiddenCouponPic];
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
}


@end
